package sucre

import groovy.xml.MarkupBuilder

class PerfilController {

    def loginService
    def beforeInterceptor = [action:this.&auth]
    def auth = {
        if(!loginService.validarAcceso(session["seguridad_usuario"],session["seguridad_funcionesHabilitadas"],controllerName,actionName,request.getRemoteAddr().toString()))
        {
            redirect(controller:"login",action:"auth",params:['acceso':false])
            return false
        }
    }

    def parametersService

    def index = {
    }

    def buildMenu(List ls){
        String html='<ul id="mit">'
        ls.each{
            if(!it.padre)
            html+=buildChilds(ls,it)
        }
        html+='</ul>'
        return html
    }
    def buildChilds(List ls,AccionMenu accion){
        String html=''
        def childs=findChilds(ls,accion)
        if(childs.size()>0){
            html+='<li><span class="ch" onclick="showul(this)" id="'+accion.id+'">&nbsp;</span><span class="desc"><input type="checkbox" name="itAcciones" value="'+accion.id+'" parent="'+((accion.padre)?accion.padre.id:0)+'" />&nbsp;'+accion.descripcion+'</span><ul class="hi" id="_'+accion.id+'">'
            childs.each{
                html+=buildChilds(ls,it)
            }
            html+='</ul></li>'
        }else{
            html+='<li><span class="sh" onclick="showul(this)" id="'+accion.id+'">&nbsp;</span><span class="desc"><input type="checkbox" name="itAcciones" value="'+accion.id+'" parent="'+((accion.padre)?accion.padre.id:0)+'"/>&nbsp;'+accion.descripcion+'</span><li>'
        }
        return html
    }
    def findChilds(ls,AccionMenu accion){
        def childs=[]
        ls.each{
            if(it.padre==accion && it.visible==true){
                childs.add(it)
            }
        }
        return childs
    }
    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']


    def list = {
        params.max=parametersService.getInt("paginacion.maxRegPagina")
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def query={
            if(params.searchField){
                ilike('nombre','%'+params.searchField+'%')
            }
        }
        if(!params.sort){
            params.sort='id'
            params.order='asc'
        }
        def perfilList=Perfil.createCriteria().list(params,query)
        [ perfilInstanceList:perfilList, perfilInstanceTotal: perfilList.getTotalCount()]
    }

    def delete = {
        println "Delete..."
        def perfilInstance = Perfil.get(params.id)
        buildSessionForMenu()
        def html=buildMenu(session.seguridad_AccionesMenuDef)

        if(perfilInstance) {
            try {
                perfilInstance.delete(flush:true)
                flash.message = "Perfil ${perfilInstance} borrado"
                render(view:'create',model:[upd:'si',perfilInstance:new Perfil(),arbol:html])
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Perfil ${perfilInstance} no puede ser borrado"
                render(view:'create')
            }
        }
        render(view:'create',model:[upd:'si',perfilInstance:new Perfil(),arbol:html])
    }
    def buildSessionForMenu(){
        if(!session.seguridad_AccionesMenuDef){
            session.seguridad_AccionesMenuDef=AccionMenu.createCriteria().list{
                eq('visible',true)
                order('orden','asc')
            }
        }
    }
    def create = {
        def perfilInstance = new Perfil()
        perfilInstance.properties = params

        buildSessionForMenu()


        def html=buildMenu(session.seguridad_AccionesMenuDef)
        def accionsSelecteds=[]

        String eOc='create'
        if(params.eOc=='edit'){
            perfilInstance=Perfil.findById(params.id)
            accionsSelecteds=perfilInstance.acciones
            eOc='edit'
        } else{
            flash.message=''
        }
        return ['perfilInstance':perfilInstance,eOc:eOc,arbol:html,'accionsSelecteds':accionsSelecteds]
    }

    def save = {
        def perfilInstance = new Perfil(params)
        if(params.eOc=='edit'){
            perfilInstance=Perfil.get(params.id)
            perfilInstance.properties=params

        }
        def acciones=[]
        if(params.itAcciones){
            params.itAcciones.each{
                def accion=AccionMenu.findById(new Integer(it))
                acciones.add(accion)
            }
        }
        perfilInstance.acciones=acciones

        if(!perfilInstance.hasErrors() && perfilInstance.save()) {
            flash.message="Perfil ${perfilInstance} "+((params.eOc=='create')?'creado':'actualizado')
            if(params.eOc=='create'){
                params.eOc='edit'
            }
        }
        buildSessionForMenu()
        def html=buildMenu(session.seguridad_AccionesMenuDef)

        def accionsSelecteds=[]
        if(perfilInstance.acciones){
            accionsSelecteds=perfilInstance.acciones;
        }
        render(view:'create',model:[perfilInstance:perfilInstance,eOc:params.eOc,upd:'si',arbol:html,'accionsSelecteds':accionsSelecteds])
    }
    def search={
        redirect(action:list,params:[searchField:params.searchField])
    }
}
